/**
 * 用户管理服务
 */

import { UserRole } from '@/stores/userStore'

// 用户接口
export interface User {
  id: number
  username: string
  name: string
  role: string
  department: string
  email: string
  phone: string
  createTime: string
  lastLogin: string
  status: 'active' | 'inactive'
}

// 新用户接口
export interface NewUser {
  username: string
  name: string
  password: string
  role: string
  department: string
  email: string
  phone: string
  status: 'active' | 'inactive'
}

// 更新用户接口
export interface UpdateUser {
  id: number
  name?: string
  password?: string
  role?: string
  department?: string
  email?: string
  phone?: string
  status?: 'active' | 'inactive'
}

// 模拟用户数据
let users: User[] = [
  {
    id: 1,
    username: 'admin',
    name: '系统管理员',
    role: UserRole.ADMIN,
    department: '信息技术部',
    email: 'admin@example.com',
    phone: '13800138000',
    createTime: '2023-01-01 08:00:00',
    lastLogin: '2023-04-29 10:15:30',
    status: 'active'
  },
  {
    id: 2,
    username: 'zhangsan',
    name: '张三',
    role: UserRole.USER,
    department: '应急管理局',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    createTime: '2023-01-02 09:30:00',
    lastLogin: '2023-04-28 14:20:10',
    status: 'active'
  },
  {
    id: 3,
    username: 'lisi',
    name: '李四',
    role: UserRole.MANAGER,
    department: '地质灾害监测中心',
    email: 'lisi@example.com',
    phone: '13800138002',
    createTime: '2023-01-03 10:45:00',
    lastLogin: '2023-04-29 09:05:22',
    status: 'active'
  },
  {
    id: 4,
    username: 'wangwu',
    name: '王五',
    role: UserRole.USER,
    department: '巴州区应急管理局',
    email: 'wangwu@example.com',
    phone: '13800138003',
    createTime: '2023-01-04 11:20:00',
    lastLogin: '2023-04-27 16:30:45',
    status: 'inactive'
  },
  {
    id: 5,
    username: 'zhaoliu',
    name: '赵六',
    role: UserRole.USER,
    department: '恩阳区应急管理局',
    email: 'zhaoliu@example.com',
    phone: '13800138004',
    createTime: '2023-01-05 14:10:00',
    lastLogin: '2023-04-26 11:45:18',
    status: 'active'
  }
]

/**
 * 获取所有用户
 * @returns 用户列表
 */
export async function getUsers(): Promise<User[]> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  return [...users]
}

/**
 * 获取用户详情
 * @param id 用户ID
 * @returns 用户详情
 */
export async function getUserById(id: number): Promise<User | null> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  const user = users.find(u => u.id === id)
  return user ? { ...user } : null
}

/**
 * 获取用户详情（通过用户名）
 * @param username 用户名
 * @returns 用户详情
 */
export async function getUserByUsername(username: string): Promise<User | null> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  const user = users.find(u => u.username === username)
  return user ? { ...user } : null
}

/**
 * 添加用户
 * @param user 新用户信息
 * @returns 添加的用户
 */
export async function addUser(user: NewUser): Promise<User> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 检查用户名是否已存在
  const existingUser = users.find(u => u.username === user.username)
  if (existingUser) {
    throw new Error('用户名已存在')
  }
  
  // 创建新用户
  const newUser: User = {
    id: Math.max(...users.map(u => u.id), 0) + 1,
    username: user.username,
    name: user.name,
    role: user.role,
    department: user.department,
    email: user.email,
    phone: user.phone,
    createTime: new Date().toLocaleString(),
    lastLogin: '-',
    status: user.status
  }
  
  // 添加到用户列表
  users.push(newUser)
  
  return { ...newUser }
}

/**
 * 更新用户
 * @param user 更新的用户信息
 * @returns 更新后的用户
 */
export async function updateUser(user: UpdateUser): Promise<User | null> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 查找用户
  const index = users.findIndex(u => u.id === user.id)
  if (index === -1) {
    return null
  }
  
  // 更新用户信息
  const updatedUser = {
    ...users[index],
    ...user
  }
  
  // 更新用户列表
  users[index] = updatedUser
  
  return { ...updatedUser }
}

/**
 * 删除用户
 * @param id 用户ID
 * @returns 是否删除成功
 */
export async function deleteUser(id: number): Promise<boolean> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 查找用户
  const index = users.findIndex(u => u.id === id)
  if (index === -1) {
    return false
  }
  
  // 删除用户
  users.splice(index, 1)
  
  return true
}

/**
 * 更新用户状态
 * @param id 用户ID
 * @param status 新状态
 * @returns 更新后的用户
 */
export async function updateUserStatus(id: number, status: 'active' | 'inactive'): Promise<User | null> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  
  // 查找用户
  const index = users.findIndex(u => u.id === id)
  if (index === -1) {
    return null
  }
  
  // 更新用户状态
  users[index].status = status
  
  return { ...users[index] }
}

/**
 * 用户登录
 * @param username 用户名
 * @param password 密码
 * @returns 登录成功的用户
 */
export async function login(username: string, password: string): Promise<User | null> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 在实际应用中，这里应该发送请求到后端进行身份验证
  // 这里简化处理，只检查用户名是否存在
  const user = users.find(u => u.username === username)
  
  if (user && user.status === 'active') {
    // 更新最后登录时间
    const index = users.findIndex(u => u.id === user.id)
    users[index].lastLogin = new Date().toLocaleString()
    
    return { ...users[index] }
  }
  
  return null
}

/**
 * 用户注册
 * @param username 用户名
 * @param password 密码
 * @param name 姓名
 * @param department 部门
 * @param email 邮箱
 * @param phone 手机
 * @returns 注册成功的用户
 */
export async function register(
  username: string,
  password: string,
  name: string,
  department: string,
  email: string,
  phone: string
): Promise<User | null> {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 检查用户名是否已存在
  const existingUser = users.find(u => u.username === username)
  if (existingUser) {
    throw new Error('用户名已存在')
  }
  
  // 创建新用户（注册用户只能是普通用户角色）
  const newUser: User = {
    id: Math.max(...users.map(u => u.id), 0) + 1,
    username,
    name,
    role: UserRole.USER, // 注册用户只能是普通用户角色
    department,
    email,
    phone,
    createTime: new Date().toLocaleString(),
    lastLogin: new Date().toLocaleString(),
    status: 'active'
  }
  
  // 添加到用户列表
  users.push(newUser)
  
  return { ...newUser }
}

/**
 * 获取可用角色列表
 * @returns 角色列表
 */
export function getRoles(): { value: string, label: string }[] {
  return [
    { value: UserRole.ADMIN, label: '系统管理员' },
    { value: UserRole.MANAGER, label: '管理人员' },
    { value: UserRole.USER, label: '普通用户' }
  ]
}

/**
 * 获取用户状态列表
 * @returns 状态列表
 */
export function getStatuses(): { value: string, label: string }[] {
  return [
    { value: 'active', label: '正常' },
    { value: 'inactive', label: '禁用' }
  ]
}
